package org.example.oop.thread;

import lombok.SneakyThrows;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description 线程安全
 * @since 2025/6/22
 */
public class SyncThreadDemo {

    public static int ticket = 0;

    private static Object lock = new Object();

    private static int total = 1000000;

    public static void main(String[] args) {

        for (int i = 0; i < 4; i++) {
            new Thread(new Runnable() {
                @Override
                @SneakyThrows
                public void run() {
                    System.out.println("线程：" + Thread.currentThread().getName());
                    while (ticket < total) {
                        // 线程睡眠,方便其他线程抢占锁,不然的话电脑运行速度很快,可能其他线程还没有抢到锁程序就跑完了
                        // Thread.sleep(1);
                        synchronized (lock) {
                            if (ticket < total) {
                                System.out.println(Thread.currentThread().getName() + "正在卖第" + (++ticket) + "张票");
                            }
                        }
                    }
                }
            }, "线程" + i).start();
        }
    }
}
